﻿var number = 4;
var current = 1;
var shop = [];
var index = 0;
var isScroll = true;
var isLogin = false;
var isSearch = false;
var cat = "All";

//Initial function which will run first when document ready
function Initial() {
    Login();
    ShowOrHideShopCart(false);
    GetMoreData();
    LoadMoreDataWhenScroll();
    AddCategories();
    $('#new-items').click(function () {
        isScroll = true;
        isSearch = false;
        GetNewItems(3);
        window.current = 1;
        isScroll = true;
    });
    $('#favorite-btn').click(function () {
        GetFavoritesItems(10);
        window.current = 1;
        isScroll = true;
        isSearch = false;
    });
    $('#home-btn').click(function () {
        window.current = 1;
        window.cat = "All";
        isScroll = true;
        isSearch = false;
        GetMoreData();
    });
    $('#logo-btn').click(function () {
        window.current = 1;
        window.cat = "All";
        isScroll = true;
        isSearch = false;
        GetMoreData();
    });
    $('#checkout-button').click(function () {
        $('#checkout-title').show();
        CreateContract($('#total').html());
        isScroll = false;
        isSearch = false;
    });
    $('#checkout-title').hide();
    $('#btn-search').click(function () {
        $('.center_content').html('');
        isSearch = true;
        SearchByItemName();
    });
    $("#backtotop").click(function () {
        $("html, body").animate({ scrollTop: 0 }, 1000);
    });
}

//Show date time
function ShowDateTime() {
    $('#date-contract').datepicker();
    $('#date-contract-img').click(function () {
        $('#date-contract').focus();
    });
    $('#date-party').datepicker();
    $('#date-party-img').click(function () {
        $('#date-party').focus();
    });
}

//add more food&drink on page
function addProduct(p) {
    if (p.Name.length > 10) p.Name = p.Name.substring(0, 10) + '...';
    if (p.Descriptions == null) p.Descriptions = 'Ngon số 1 Việt Nam. Hãy đến và cảm nhậm sự khác biệt. Đặt hàng ngay để được giảm giá.Chúng tôi là số 1. Hãy gọi cho chúng tôi !';
    if (p.Descriptions.length > 150) p.Descriptions = p.Descriptions.substring(0, 150) + '...';
    var obj = $('.center_content');
    if (p.Type === 'Food') {
        $(obj).append('<div class="items">' +
    '<div class="image-con">' +
    '<a href="javascript:;">' +
    '<img onclick = GoToFoodDetails(' + p.ItemId + ') alt="" src="../../Content/Images/Uploads/' + p.Image + '" /></a>' +
    '</div><div class="info"><span class="title">' +
    '<a href="javascript:;">' + p.Name + '</a>' +
    '</span><span class="cat">' + p.Type + '</span>' +
    '<span class="price">' + p.StandardPrice + ' $</span><span class="cart-shop">' +
    '<img onclick=AddFoodtoCart(' + p.ItemId + ') alt="" src="../../images/cart.gif" /></span>' +
    '<span class="likes"><a href="javascript:;"onclick = GoToFoodDetails(' + p.ItemId + ')>View</a></span>' +
    '</div><div class="description"><p>' + p.Descriptions + '</p></div></div>');
    } else {
        $(obj).append('<div class="items">' +
    '<div class="image-con">' +
    '<a href="javascript:;">' +
    '<img onclick = GoToDrinkDetails(' + p.ItemId + ') alt="" src="../../Content/Images/Uploads/' + p.Image + '" /></a>' +
    '</div><div class="info"><span class="title">' +
    '<a href="javascript:;">' + p.Name + '</a>' +
    '</span><span class="cat">' + p.Type + '</span>' +
    '<span class="price">' + p.StandardPrice + ' $</span><span class="cart-shop">' +
     '<img onclick=AddDrinktoCart(' + p.ItemId + ') alt="" src="../../images/cart.gif" /></span>' +
    '<span class="likes"><a href="javascript:;"onclick = GoToDrinkDetails(' + p.ItemId + ')>View</a></span>' +
    '</div><div class="description"><p>' + p.Descriptions + '</p></div></div>');
    }
}

//Add food item to shopcart
function Sum() {
    var s = 0;
    $('#checkout-table tr').each(function () {
        try {
            var c = $(this).find('td').eq(3).find('input').val();
            var p = $(this).find('td').eq(4).html();
            p = p.substring(0, p.length - 1);
            if (typeof p != 'undefined') {
                if (typeof c != 'undefined') {
                    s += eval(p) * eval(c);
                }
            }
        } catch (e) {

        }

    });
    $('#total-items').html(s + '$');
}

//Update count items
function UpdateCountChange() {
    $('.count').change(function () {
        Sum();
    });
}
//Add drink item to shopcart
function AddDrinktoCart(id) {
    $.ajax({
        type: 'post',
        url: '/Home/GetDrinkDetailsById',
        data: { id: id },
        dataType: 'json',
        async: false,
        success: function (data) {
            if (isLogin) {
                $('#count').html(eval($('#count').html()) + 1);
                $('#total').html(eval($('#total').html().substring(0, $('#total').html().length - 1)) + data[0].StandardPrice + '$');
                shop[index] = { Id: data[0].DrinkId, Name: data[0].Name, Cat: data[0].DrinkTypeName, Price: data[0].StandardPrice, Exist: 'false', Type: 'Drink' };
                index++;
            }
        }
    });
}

//Add food item to shopcart
function AddFoodtoCart(id) {
    $.ajax({
        type: 'post',
        url: '/Home/GetFoodDetailsById',
        data: { id: id },
        async: false,
        dataType: 'json',
        success: function (data) {
            if (isLogin) {
                $('#count').html(eval($('#count').html()) + 1);
                $('#total').html(eval($('#total').html().substring(0, $('#total').html().length - 1)) + data[0].StandardPrice + '$');
                shop[index] = { Id: data[0].FoodId, Name: data[0].Name, Cat: data[0].FoodTypeName, Price: data[0].StandardPrice, Exist: 'false', Type: 'Food' };
                index++;
            }
        }
    });
}
//Redirect to food details of item
function GoToFoodDetails(id) {
    $.ajax({
        type: 'post',
        url: '/Home/GetFoodDetailsById',
        data: { id: id },
        async: false,
        dataType: 'json',
        success: function (data) {
            $('.center_content').html('<div class="items-details"><div class="image-con-details">' +
                '<a href="javascript:;"><img alt="" src="../../Content/Images/Uploads/' + data[0].Image + '"/></a>' +
                '</div><div class="info"><span class="title-details">' +
                '<a href="javascript:;">' + data[0].Name + '</a></span>' +
                '<span class="price-details">' + data[0].StandardPrice + '$</span><img class="icon-new-details" src="../../Content/Images/Defaults/new.png" alt=""/>' +
                '<span class="cart-shop-details"><img onclick=AddFoodtoCart(' + data[0].FoodId + ') alt="" src="../../Content/Images/Defaults/shopcart.png"/>' +
                '</span></div><div class="description-details">' +
                '<p>Ngon số 1 Việt Nam. Hãy đến và cảm nhậm sự khác biệt. Đặt hàng ngay để được giảm giá.Chúng tôi là số 1. Hãy gọi cho chúng tôi !</p></div></div>');
        }
    });
}

//Redirect to food details of item
function GoToDrinkDetails(id) {
    $.ajax({
        type: 'post',
        url: '/Home/GetDrinkDetailsById',
        data: { id: id },
        dataType: 'json',
        async: false,
        success: function (data) {
            $('.center_content').html('<div class="items-details"><div class="image-con-details">' +
                '<a href="javascript:;"><img alt="" src="../../Content/Images/Uploads/' + data[0].Image + '"/></a>' +
                '</div><div class="info"><span class="title-details">' +
                '<a href="javascript:;">' + data[0].Name + '</a></span>' +
                '<span class="price-details">' + data[0].StandardPrice + '$</span><img class="icon-new-details" src="../../Content/Images/Defaults/new.png" alt=""/>' +
                '<span class="cart-shop-details"><img onclick=AddDrinktoCart(' + data[0].DrinkId + ') alt="" src="../../Content/Images/Defaults/shopcart.png"/>' +
                '</span></div><div class="description-details">' +
                '<p>Ngon số 1 Việt Nam. Hãy đến và cảm nhậm sự khác biệt. Đặt hàng ngay để được giảm giá.Chúng tôi là số 1. Hãy gọi cho chúng tôi !</p></div></div>');
        }
    });
}

//load more food&drink when scroll
function LoadMoreDataWhenScroll() {
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() >= $(document).height() - 50) {
            window.current++;
            GetMoreData();
        }
    });
}

//add categories from database
function AddCategories() {
    var obj = $('.left_menu');
    $(obj).html('');
    $.ajax({
        type: 'post',
        url: '/Home/GetAllCategories',
        data: {},
        async: false,
        dataType: 'json',
        success: function (data) {
            $(obj).html(' <li class="even"><a href="javascript:;" onclick=ClickCategoryEvent(this)>All</a></li>');
            for (var i = 0; i < data.length ; i++) {
                if (i % 2 == 0) {
                    $(obj).append(' <li class="odd"><a href="javascript:;" onclick=ClickCategoryEvent(this)>' + data[i].Name + '</a></li>');
                } else {
                    $(obj).append(' <li class="even"><a href="javascript:;" onclick=ClickCategoryEvent(this)>' + data[i].Name + '</a></li>');
                }
            }
        }
    });

}

//todo when click specify category
function ClickCategoryEvent(obj) {
    cat = $(obj).text();
    current = 1;
    isScroll = true;
    isSearch = false;
    $('.center_content').html('');
    GetMoreData();
}

//show or hide shop-cart when login
function ShowOrHideShopCart(p) {
    if (!p) $('.shopping_cart').hide();
    else $('.shopping_cart').show();
}

//get new items
function GetNewItems(n) {
    $('.center_content').html('');
    $.ajax({
        type: 'post',
        async: false,
        url: '/Home/GetNewItem',
        data: { n: n },
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < n; i++) {
                addProduct(data[i]);
            }
        }
    });
}

//Get favorites items
function GetFavoritesItems(n) {
    $('.center_content').html('');
    $.ajax({
        type: 'post',
        url: '/Home/GetFavoritesItem',
        data: { n: n },
        async: false,
        dataType: 'json',
        success: function (data) {
            for (var i = 0; i < n; i++) {
                addProduct(data[i]);
            }
        }
    });
}

//Get items from database
function GetMoreData() {
    if (isScroll == true && isSearch == false) {
        $.ajax({
            type: 'post',
            async: false,
            url: '/Home/GetMoreData',
            data: { number: number, current: current, cat: cat },
            dataType: 'json',
            success: function (data) {
                for (var i = 0; i < data.length; i++) {
                    addProduct(data[i]);
                }
            }
        });
    }
}

function Login() {
    $('#btn-login').click(function () {
        $.ajax({
            type: 'post',
            async: false,
            url: '/Home/CheckLogin',
            data: { user: $('#txt-account').val(), pass: $('#txt-password').val() },
            dataType: 'json',
            success: function (result) {
                if (result == '') {
                    $('#txt-account').css('border', 'solid 1px red');
                    $('#txt-password').css('border', 'solid 1px red');
                } else {
                    if (result[0].IsAdmin) {
                        $('#login-table').html(' <tr><td>Wellcome</td><td>' + result[0].Name + '</td></tr><tr><td>Level</td><td>' + 'Admin' + '</td></tr><tr><td><input type="button" value="Logout" onclick="Logout()"/></td></tr>');
                        $('#admin-task').show();
                    } else {
                        $('#login-table').html(' <tr><td>Wellcome</td><td>' + result[0].Name + '</td></tr><tr><td>Level</td><td>' + 'Member' + '</td></tr><tr><td><input type="button" value="Logout" onclick="Logout()"/></td></tr>');
                    }
                    ShowOrHideShopCart(true);
                    isLogin = true;
                    index = 0;
                    $('#count').html('0');
                    $('#total').html('0$');
                    shop = [];
                }
            }
        });
    });
}

//Logout 
function Logout() {
    $('#login-table').html('<tr><td>Account</td><td><input type="text" id="txt-account"/></td></tr><tr><td>Password</td><td><input type="password" id="txt-password"/></td></tr><tr><td><input type="button" value="Login" id="btn-login"/></td><td><a href="javascript:;">Register</a></td></tr>');
    Login();
    ShowOrHideShopCart(false);
    isLogin = false;
    window.current = 1;
    window.cat = "All";
    isScroll = true;
    isSearch = false;
    $('.center_content').html('');
    GetMoreData();
    $('#admin-task').hide();
}

//Search by item Name
function SearchByItemName() {
    $.ajax({
        type: 'post',
        url: '/Home/SearchByItemName',
        data: { name: $('#txt-search').val() },
        dataType: 'json',
        async: false,
        success: function (result) {
            isScroll = true;
            for (var i = 0; i < result.length; i++) {
                addProduct(result[i]);
            }
        }
    });
}

//Create contract
function CreateContract(amount) {
    $('.center_content').html('<span id="contract-title">Contract</span><table id="contract-table"><tr><td style="display:none">Contract Date</td><td style="display:none"><input id="date-contract" type="text"/></td><td><img style="display:none" id="date-contract-img" alt="" src="../../Content/Images/Defaults/date.png"/></td></tr><tr><td>Party Date</td><td><input id="date-party" type="text"/></td><td><img id="date-party-img" alt="" src="../../Content/Images/Defaults/date.png"/></td></tr><tr><td>Party Address</td><td><input id="txt-party-address" type="text"/></td></tr><tr><td>Party Type</td><td><select id="txt-party-type"><option>Party vip</option><option>Party normal</option></select></td></tr><tr><td>Promotion</td><td><textarea id="txt-promotion"></textarea></td></tr><tr><td>Party Consultancy</td><td><input id="txt-party-consultancy" type="text"/></td></tr><tr><td>Party Setup Style</td><td><input id="txt-party-setup" type="text"/></td></tr><tr><td>Payment Method</td><td><select id="txt-payment-method"><option>Card</option><option>Money</option><option>Credit</option></select></td></tr><tr><td>Transportation Vehicle</td><td><input id="txt-vehicle" type="text"/></td></tr><tr><td>Discount</td><td><input id="txt-discount" type="text"/></td></tr><tr><td>Older Amount</td><td><input id="txt-old-amount" type="text"/></td></tr><tr><td>Child Amount</td><td><input id="txt-child-amount" type="text"/></td></tr><tr><td>Customer Amount PerTable</td><td><input id="cus-amount-table" type="text"/></td></tr><tr><td>Other Requirements</td><td><textarea id="others-requiment"></textarea></td></tr><tr><td style="font-size: 35px">Total</td><td><p style="color: red;font-size: 50px;" id="contract-total">1200$</p></td></tr><tr><td></td><td></td><td><input id="send-btn" type="button" value="Send"/></td></tr></table>');
    $('#contract-total').html(amount);
    ShowDateTime();
    $('#send-btn').click(function () {
        isScroll = false;
        isSearch = true;
        InsertContract();
    });
}

//Get Order party
function GetOrder(contractId) {
    $.ajax({
        type: 'post',
        url: '/Home/GetOrderParty',
        data: { contractId: contractId },
        dataType: 'json',
        async: false,
        success: function (result) {
            $('#txt-staff-phone').val(result[0].PhoneNumber);   
            $('#txt-cus-company').val(result[0].OrganizationName);
            $('#txt-cus-address').val(result[0].OrganizationAddress);
            $('#clock_atxt-cus-phone').val(result[0].CustPhone);
            //$('#txt-date').val(result[0].PartyDate);
        }
    });
}
//Insert Contract
function InsertContract() {
    var contract = '1@1@' + '' + '@' + $('#date-party').val() + '@' +
        $('#txt-party-address').val() + '@' + $('#txt-party-type option:selected').text() + '@' + $('#txt-promotion').val() + '@' +
        $('#txt-party-consultancy').val() + '@' + $('#txt-party-setup').val() + '@' + $('#txt-payment-method option:selected').text() + '@' +
        $('#txt-vehicle').val() + '@' + $('#txt-discount').val() + '@' + $('#txt-old-amount').val() + '@' +
        $('#txt-child-amount').val() + '@' + $('#cus-amount-table').val() + '@' + $('#others-requiment').val() + '@' + $('#contract-total').html().replace('$', '');
    $.ajax({
        type: 'post',
        url: '/Home/InsertContract',
        data: { obj: contract },
        async: false,
        dataType: 'json',
        success: function (result) {
            if (result != -1) {
                isScroll = true;
                isSearch = false;
                CreateCheckOutList(result);
                InsertToContractDetails(result);
                GetOrder(result);
            } else {
                alert('Please insert infomation before click send !');
            }
        }
    });
}

//Create notification
function CreateNotification() {
    $('.center_content').html('');
    isScroll = true;
    isSearch = false;
    GetMoreData();
    //$('.center_content').html(' <div id="notification"><span id="title-notification">Send contract successfull!</span><input type="button" value="Download" id="download-btn"/></div>');
}

//insert to contract-food

function InsertToContractDetails(contractId) {
    $('#checkout-table tr').each(function () {
        try {
            var id = $(this).find('td').eq(0).html();
            var t = $(this).find('td').eq(5).html();
            var c = $(this).find('td').eq(3).find('input').val();
            var p = $(this).find('td').eq(4).html();
            p = p.substring(0, p.length - 1);
            if (typeof p != 'undefined') {
                if (typeof c != 'undefined') {
                    var obj = contractId + '@' + id + '@' + c + '@' + p;
                    if (t == 'Drink') {
                        $.ajax({
                            type: 'post',
                            url: '/Home/InsertToContractDrink',
                            data: { obj: obj },
                            dataType: 'json',
                            async: false,
                            success: function () {

                            }
                        });
                    } else {
                        $.ajax({
                            type: 'post',
                            url: '/Home/InsertToContractFood',
                            data: { obj: obj },
                            dataType: 'json',
                            async: false,
                            success: function () {

                            }
                        });
                    }
                }
            }
        } catch (e) {

        }
    });
}

//Create checkout list
function CreateCheckOutList() {
    $('.center_content').html('<div id="bill"><div id="logo-bill"><img alt="" src="../../Content/Images/Defaults/img.jpg"/></div><div id="header-bill"><span id="title-bill">HAIWAII RESTAURENT</span><span id="address-bill">127 Nguyễn Khoái - Đàm Trấu - Hà Nội</span><span id="tel-bill">Tel: <span style="color: red">04.398.449.86</span> – Fax: <span style="color: red">04.398.449.48</span></span><span id="email-bill">Email: info@support.com</span><span id="web-bill">Website: www.phonuonghawaii.com</span></div><div id="content-bill"><span id="title-content-bill">ORDER PARTY COMFIRM</span><table id="bill-table"><tr><td>Representative of the restaurant</td><td><input id="txt-restaurent" type="text"/></td></tr><tr><td>Title</td><td><input type="text"/></td><td>Telephone</td><td><input id="txt-staff-phone" type="text"/></td></tr><tr><td>Representative of guest</td><td><input id="txt-guest" type="text"/></td></tr><tr><td>Company name</td><td><input id="txt-cus-company" type="text"/></td></tr><tr><td>Address</td><td><input id="txt-cus-address" type="text"/></td></tr><tr><td>Telephone</td><td><input id="txt-cus-phone" type="text"/></td><td>Fax</td><td><input id="txt-cus-fax" type="text"/></td></tr><tr><td>Reservation date</td><td><input id="txt-date" type="text"/></td><td>Time</td><td><input id="txt-time"type="text"/></td></tr><tr><td>Number of guests</td><td><input id="txt-number" type="text"/></td><td>Type of banquet</td><td><input id="txt-banquet" type="text"/></td></tr><tr><td>Deposit</td><td><input id="txt-deposit" type="text"/></td><td>In word</td><td><input id="txt-word" type="text"/></td></tr></table></div></div>');
    $('.center_content').append(' <span id="checkout-title">Menu Confirmation</span><table id="checkout-table"><tr><th>ID</th><th>Name</th><th>Category</th><th>Count</th><th>Price</th><th>Type</th></tr>');
    var i;
    for (i = 0; i < shop.length; i++) {
        var count = 1;
        if (shop[i].Exist == 'false') {
            for (var j = i + 1; j < shop.length; j++) {

                if (shop[j].Exist == 'false' && shop[j].Name == shop[i].Name && shop[j].Price == shop[i].Price) {
                    count++;
                    shop[j].Exist = 'true';
                }
            }
        }
        if (shop[i].Exist == 'false') {
            $('#checkout-table').append('<tr><td>' + shop[i].Id + '</td><td>' + shop[i].Name + '</td><td>' + shop[i].Cat + '</td><td><input type="text" class="count" value="' + count + '"/></td><td>' + shop[i].Price + '$</td><td>' + shop[i].Type + '</td></tr>');
            shop[i].Exits = 'true';
        }
    }
    for (i = 0; i < shop.length; i++) shop[i].Exist = 'false';
    $('#checkout-table').append('<tr><td style="font-size: 20px;">Totals</td><td id="total-items">0$</td><td></td><td></td><td><input type="button" value="Order" onclick="Sum()" id="order-btn"/></td></tr></table>');
    $('#total-items').html($('#total').html());
    UpdateCountChange();
    $('#order-btn').click(function () {
        CreateNotification();
    });
}